package com.malred;

import java.util.Arrays;

/**
 * @author malguy-wang sir
 * @create ---
 */
public class myArrayList<T> {
    //存放元素的数组
    private Object[] elementData;
    //当前数组元素个数
    private int size;

    public myArrayList() {
    }

    //默认初始容量
    private final int DEFAULT_CAPACITY = 10;

    //添加方法
    public void add(T t) {
        if (elementData == null) {
            //为空的时候初始化
            elementData = new Object[DEFAULT_CAPACITY];
        }
        //如果需要扩容
        if (toGrow(size + 1)) grow();
        elementData[size++] = t;//添加
    }

    //扩容
    private void grow() {
        int length = (int) (elementData.length * 1.5);
        elementData = Arrays.copyOf(elementData, length);
    }

    //是否需要扩容
    public boolean toGrow(int length) {
        //如果size+1大于当前数组总长度
        if (length - elementData.length > 0) return true;
        return false;
    }

    //取出方法
    public T get(int index) {
        return (T) elementData[index];
    }

    //删除
    public void remove(Object o) {
        for (int i = 0; i < size; i++) {
            if (o.equals(elementData[i])) {
                //被删除的那位后面有多少个
                int remove = size - i - 1;
                if (remove > 0) {
                    //从第i+1位后面开始复制到新数组第i位后面
                    System.arraycopy(elementData, i + 1, elementData, i, remove);
                    //缩容--size不会出现下标超出长度
                    elementData[--size] = null;
                }
            }
        }
    }
    public void show(){
        System.out.println(Arrays.toString(elementData));
    }
    //test
    public static void main(String[] args) {
        myArrayList<String> list = new myArrayList<>();
        for (int i = 0; i < 15; i++) {
            list.add(i + "");
        }
        list.show();
        list.remove("2");
        list.show();
    }
}
